import EventEmitter from 'events';
import LoRa from 'lora';
import { LoRaDeviceInfo } from './type';

class LoraManager extends EventEmitter {
  private readonly chunkSize = 24;
  private lora: LoRa | null = null;
  devs: LoRaDeviceInfo[] = [];
  status = false;

  constructor() {
    super()
    this.initInstance()
    this.list();
    setInterval(() => this.list(), 10 * 1000) // 定期获取设备列表
  }

  initInstance() {
    try {
      if (!this.lora) {
        this.lora = new LoRa();
        this.lora.on('message', (devEUI: string, data: Buffer) => {
          try {
            console.log('lora message: ', devEUI, data, data.toString())
          } catch (error) {
            console.error(error)
          }


          // this.emit('message', devEUI, data.toString('hex'))
        })
        this.lora.on('failed', (devEUI: string, error: Error) => {
          // publish 发送消息需要请求响应时候，没有收到Lora设备的响应数据
          console.error('lora failed')
          this.emit('failed', devEUI, error);
        })
        this.lora.subscribe(); // 直接订阅所有lora设备
        this.status = true
        return { result: true, message: '实例化lora对象成功！' }
      }
    } catch (error) {
      console.error('initInstance error.')
      return { result: false, message: '实例化lora对象失败！' }
    }
  }

  close() {
    this.lora && this.lora.close();
  }

  sendMessage(devEUI: string, buf: Buffer) {
    if (this.lora) {
      if (buf.length <= this.chunkSize) {
        console.log('Overall transmission: ', devEUI, Object.prototype.toString.call(buf))
        this.lora.publish(devEUI, buf, false, (err) => {
          console.log('publish: ', err)
        });
      } else {
        /* 分块发送 */
        console.log('Block transmission')
      }
    }
  }

  /* 订阅（所有）设备消息 */
  subscribe(devEUI?: string) {
    this.lora && this.lora.subscribe(devEUI);
  }

  /* 取消订阅（所有）设备消息 */
  unsubscribe(devEUI?: string) {
    this.lora && this.lora.unsubscribe(devEUI);
  }

  /* 获取当前连接到网络的lora设备列表 */
  private list() {
    LoRa.list((error, list) => {
      if (error) {
        console.error(error.message);
      } else {
        this.devs = list;
        this.emit('list', this.devs);
        if (this.lora) {
          this.lora.subscribe(); // 直接订阅所有lora设备
          list.map((item) => {
            this.lora.subscribe(item.devEUI)
          })
        }
      }
    });
  }

  private uint8ArrayToString(fileData){
    var dataString = "";
    for (var i = 0; i < fileData.length; i++) {
      dataString += String.fromCharCode(fileData[i]);
    }
    return dataString
  }
}

export default new LoraManager();